#include <stdio.h>
#include "genlib.h"
#include "graphics.h"
#include "mazelib.h"
#include "simpio.h"

#define MaxPath 100
#define MazeFile "pathlen.maz"

static pointT AdjacentPoint(pointT pt, directionT dir);
int FindPath(pointT pt, pointT path[], int maxPathSize);

main() {
	int i, len;
	string filename = "";
	pointT *path;

	path = NewArray(MaxPath, pointT);
	printf("ALAL\n\nEnter name of file: \n");
	filename = GetLine();
	SetPauseTime(0);
	ReadMazeMap(filename);
	len = FindPath(GetStartPosition(), path, MaxPath);
	if (len == 0) {
		printf("No solution exists.\n");
	} else {
		printf("The following path is a solution:\n");
		for (i = len-1; i >= 0; i--) {
			printf(" (%d, %d)\n", path[i].x, path[i].y);
		}
	}
}

int FindPath(pointT pt, pointT path[], int maxPathSize) {
	directionT dir;
	int steps = 0, solution = 0;

    if (OutsideMaze(pt)) {
		path[steps] = pt;
		return 1;
	}
    if (IsMarked(pt)) return 0;
    MarkSquare(pt);
	
    for (dir = North; dir <= West; dir++) {
        if (!WallExists(pt, dir)) {			
			if (steps = FindPath(AdjacentPoint(pt, dir), path, maxPathSize)) {
				if (steps >= maxPathSize) return 0;
				path[steps] = pt;
				return (steps + 1);
			}
        }
    }
    return 0;
}

/*
 * Function: AdjacentPoint
 * Usage: newpt = AdjacentPoint(pt, dir);
 * --------------------------------------
 * This function returns the pointT that results from moving
 * one square from pt in the direction specified by dir.  For
 * example, if pt is the point (1,1), AdjacentPoint(pt, East)
 * would return the point (2,1).
 */

static pointT AdjacentPoint(pointT pt, directionT dir)
{
    pointT newpt;

    newpt = pt;
    switch (dir) {
      case North: newpt.y++; break;
      case East:  newpt.x++; break;
      case South: newpt.y--; break;
      case West:  newpt.x--; break;;
    }
    return (newpt);
}